import mysql.connector
import json
import yaml
# 数据库连接配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': '1234',
    'database': 'network',
    'charset': 'utf8'
}


def get_data_from_db(chain_id):
    try:
        # 连接到数据库
        connection = mysql.connector.connect(**DB_CONFIG)
        cursor = connection.cursor(dictionary=True)  # 使用字典游标

        # 执行查询
        query = "SELECT * FROM diaoyongchain WHERE chain_id = %s"
        cursor.execute(query, (chain_id,))

        # 获取所有结果
        results = cursor.fetchall()

        # 关闭游标和连接
        cursor.close()
        connection.close()

        return results
    except Exception as e:
        print(f"Error fetching data from database: {e}")
        return []


if __name__ == '__main__':
    chain_id = 1
    data = get_data_from_db(chain_id)

    if data:
        # print(json.dumps(data, indent=4,ensure_ascii=False))  # 以 JSON 格式打印结果
        #
        # 遍历解析后的数据
        for item in data:
            # 打印每个字典的详细信息
            # print(f"ID: {item['id']}")
            # print(f"Chain ID: {item['chain_id']}")
            # print(f"Order: {item['order']}")
            # print(f"Host Name: {item['host_name']}")
            # print(f"Host IP: {item['host_ip']}")
            # print(f"Status: {item['status']}")
            # print()  # 打印一个空行以分隔不同的项
            nodename=item['host_name']
            if nodename!="usernode":
                yamldata="""
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: testdeploy
    type: chain
  name: my-python
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-python
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: my-python
    spec:
      containers:
      - image: registry.cn-hangzhou.aliyuncs.com/k8sbupt/local:mypythonnew2
        name: my-python
        resources: {}
      nodeName: %s
status: {}
""" % nodename

                data = yaml.safe_load(yamldata)

                with open('output.yaml', 'w', encoding='utf-8') as file:
                    yaml.dump(data, file, default_flow_style=False, allow_unicode=True)

    else:
        print("No data found for chain_id = 1")